package xin.yangshuai.basic01.sse;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SseEmitterServiceImpl implements SseEmitterService {

    /**
     * 容器，保存连接，用于输出返回
     */
    private static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();

    @Override
    public SseEmitter create(String clientId) {
        SseEmitter sseEmitter = new SseEmitter(0L);
        sseCache.put(clientId, sseEmitter);
        try {
            sseEmitter.send("hello world");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sseEmitter;
    }

    @Override
    public void close(String clientId) {
        SseEmitter sseEmitter = sseCache.get(clientId);
        if (sseEmitter != null) {
            sseEmitter.complete();
            sseCache.remove(clientId);
        }
    }

    @Override
    public void sendMsgToClient(String clientId, String message) {

        SseEmitter sseEmitter = sseCache.get(clientId);
        try {
            sseEmitter.send(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendMsgToAll(String message) {

        for (Map.Entry<String, SseEmitter> sseEmitterEntry : sseCache.entrySet()) {
            SseEmitter sseEmitter = sseEmitterEntry.getValue();
            try {
                SseEmitter.SseEventBuilder sseEventBuilder = SseEmitter.event()
                        .reconnectTime(5000)
                        .id(UUID.randomUUID().toString())
                        .name("info")
                        .data(message);
                sseEmitter.send(sseEventBuilder);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
